package com.inxedu.os.edu.controller.webpage;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.inxedu.os.common.constants.CommonConstants;
import com.inxedu.os.common.controller.BaseController;
import com.inxedu.os.common.entity.PageEntity;
import com.inxedu.os.common.util.FileUtils;
import com.inxedu.os.common.util.FreeMarkerUtil;
import com.inxedu.os.common.util.ObjectUtils;
import com.inxedu.os.common.util.StringUtils;
import com.inxedu.os.edu.constants.enums.WebSiteProfileType;
import com.inxedu.os.edu.controller.Template.AdminTemplateFileController;
import com.inxedu.os.edu.entity.webpage.Webpage;
import com.inxedu.os.edu.entity.webpagetemplate.WebpageTemplate;
import com.inxedu.os.edu.entity.website.WebsiteImages;
import com.inxedu.os.edu.entity.website.WebsiteProfile;
import com.inxedu.os.edu.service.webpage.WebPagePublishThread;
import com.inxedu.os.edu.service.webpage.WebpageService;
import com.inxedu.os.edu.service.webpagetemplate.WebpageTemplateService;
import com.inxedu.os.edu.service.website.WebsiteImagesService;
import com.inxedu.os.edu.service.website.WebsiteNavigateService;
import com.inxedu.os.edu.service.website.WebsiteProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author www.inxedu.com
 * @description 页面 后台WebpageController
 */
@Controller
@RequestMapping("/admin")
public class AdminWebpageController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(AdminWebpageController.class);
	
	@Autowired
	private WebpageService webpageService;
    @Autowired
    private WebpageTemplateService webpageTemplateService;
    @Autowired
    private WebsiteImagesService websiteImagesService;
    @Autowired
    private WebsiteProfileService websiteProfileService;
    @Autowired
    private WebsiteNavigateService websiteNavigateService;

	// 绑定属性 封装参数
	@InitBinder("webpage")
	public void initWebpage(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("webpage.");
	}
	
	/** 
	 * 到页面添加页面
	 */
    @RequestMapping("/webpage/toadd")
    public ModelAndView toAddWebpage(HttpServletRequest request,ModelAndView model) {
    	model.setViewName(getViewPath("/admin/webpage/webpage_add"));
    	try{
    		
    	}catch (Exception e) {
    		model.setViewName(this.setExceptionRequest(request, e));
			logger.error("AdminWebpageController.toAddWebpage()---error",e);
		}
        return model;
    }
    /**
     * 实时发布页面
     */
    @RequestMapping("/webpage/add")
    @ResponseBody
    public  Map<String,Object> addWebpage(HttpServletRequest request, @ModelAttribute("webpage") Webpage webpage) {
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            // 添加页面
            webpage.setCreateTime(new Date());
            String templateUrlArr[]=request.getParameterValues("templateUrl");
            String templateNameArr[]=request.getParameterValues("templateName");
            String templateSortArr[]=request.getParameterValues("templateSort");
            String templateIdArr[] = request.getParameterValues("templateId");
            String infoArr[]=request.getParameterValues("info");
            String templateTitleArr[]=request.getParameterValues("templateTitle");
            //查询页面
            webpage = webpageService.getWebpageById(webpage.getId());
            WebpageTemplate webpageTemplate=new WebpageTemplate();
            webpageTemplate.setPageId(webpage.getId());
            webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
            //查询页面下所有 的模板
            List<WebpageTemplate> webpageTemplates = webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
            /*原页面对应的模板id集合*/
            List oldtemplateIdList = new ArrayList();
            /*页面当前模板的id集合*/
            List nowTemplateIdList = new ArrayList();
            for (String id:templateIdArr){
                nowTemplateIdList.add(Long.parseLong(id));
            }
            for (WebpageTemplate webpageTemplate1:webpageTemplates){
                oldtemplateIdList.add(webpageTemplate1.getId());
            }
            /*获取被删除的模板id*/
            for (int i=0;i<oldtemplateIdList.size();i++){
                if (nowTemplateIdList.contains(oldtemplateIdList.get(i))){
                    oldtemplateIdList.remove(i);
                    i=i-1;
                }
            }
            /*删除模板时，删除对应的模板图片内容*/
            for (int i=0;i<oldtemplateIdList.size();i++){
                websiteImagesService.delImagesByTemplateId(Long.parseLong(oldtemplateIdList.get(i).toString()));
            }
            //根据页面id 删除所有的 模板
            webpageTemplateService.delWebpageTemplateByWebpageId(webpage.getId());

            /*保存新的模板中间表信息*/
            if(ObjectUtils.isNotNull(templateNameArr)) {
                for (int i = 0; i < templateUrlArr.length; i++) {
                    if (StringUtils.isNotEmpty(templateUrlArr[i])) {
                        webpageTemplate.setId(null);
                        webpageTemplate.setTemplateName(templateNameArr[i]);
                        webpageTemplate.setSort(Integer.parseInt(templateSortArr[i]));
                        if (StringUtils.isNotEmpty(infoArr[i])){
                            webpageTemplate.setInfo(infoArr[i]);
                        }else {
                            webpageTemplate.setInfo(null);
                        }
                        if (StringUtils.isNotEmpty(templateTitleArr[i])){
                            webpageTemplate.setTemplateTitle(templateTitleArr[i]);
                        }else {
                            webpageTemplate.setTemplateTitle(null);
                        }
                        /*获取模板对应图片信息、并更改图片对应的模板id*/
                        WebsiteImages websiteImages = new WebsiteImages();
                        websiteImages.setWebpageTemplateId(Long.parseLong(templateIdArr[i]));
                        List<WebsiteImages> websiteImagesList = websiteImagesService.queryImageList(websiteImages);
                        /*String str2 = request.getSession().getServletContext().getRealPath("/").substring(0,request.getSession().getServletContext().getRealPath("/").lastIndexOf("\\"));
                        String t = str2.replace("\\","\\\\");
                        String str = templateUrlArr[i].replace(t,"");*/
                        webpageTemplate.setTemplateUrl(templateUrlArr[i]);
                        webpageTemplateService.addWebpageTemplate(webpageTemplate);
                        for (WebsiteImages websiteImages1:websiteImagesList){
                            websiteImages1.setWebpageTemplateId(webpageTemplate.getId());
                            websiteImagesService.updateImage(websiteImages1);
                        }
                    }
                }
            }
            webpageService.updWebpagePublish(webpage.getId(),request.getSession().getServletContext().getRealPath("/"));
            //如果发布页面为首页则生成资讯详情页面
            /*if ("/index.html".equals(webpage.getPublishUrl())){
                *//*数据库保存首页头尾、生成资讯详情页面*//*
                this.saveHederFooter(webpage);
                webpageService.publishAll(true);
            }*/
            json = this.setJson(true,webpage.getPublishUrl(),null);
        } catch (Exception e) {
            logger.error("AdminWebpageController.addWebpage()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }

    /**
     * 新增后 预览页面
     */
    @RequestMapping("/ajax/webpage/preview")
    @ResponseBody
    public  Map<String,Object> ajaxWebpagePreview(HttpServletRequest request, @ModelAttribute("webpage") Webpage webpage) {
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            String templateIdArr[] = request.getParameterValues("templateId");
            //查询页面
            webpage = webpageService.getWebpageById(webpage.getId());

            Map<String, Object> root = webpageService.getTemplateRootMap(webpage);

        /* ftl文件名*/
            String publishUrl = StringUtils.isNotEmpty(webpage.getPublishUrl())?webpage.getPublishUrl():"";
            //返回预览路径
            String returnpreviewUrl="";
            //重命名 预览 发布路径
            publishUrl=publishUrl.substring(0,publishUrl.lastIndexOf("."))+"_preview.html";
            returnpreviewUrl=publishUrl;
            publishUrl=request.getSession().getServletContext().getRealPath("/")+publishUrl;

            String ftlName = publishUrl;
            ftlName = ftlName.substring(ftlName.lastIndexOf("/")+1,ftlName.lastIndexOf("."));


            //生成模板路径
            String ftlUrl=request.getSession().getServletContext().getRealPath("/")+"/WEB-INF/ftl";

            WebpageTemplate webpageTemplateTemp=null;
            StringBuffer bodyHtml=new StringBuffer();
            if(ObjectUtils.isNotNull(templateIdArr)){
                for (String id:templateIdArr){
                    webpageTemplateTemp=webpageTemplateService.getWebpageTemplateById(Long.parseLong(id));
                    bodyHtml.append(FileUtils.readLineFile(request.getSession().getServletContext().getRealPath("/").replace("\\","/")+webpageTemplateTemp.getTemplateUrl())
                            .replace("TEMPLATE_TITLE","TEMPLATE_TITLE"+webpageTemplateTemp.getId())
                            .replace("TEMPLATE_INFO","TEMPLATE_INFO"+webpageTemplateTemp.getId())
                            .replace("WEBSITE_IMAGES_LIST","WEBSITE_IMAGES_LIST"+webpageTemplateTemp.getId())
                            .replace("TEMPLATE_ID","TEMPLATE_ID"+webpageTemplateTemp.getId())//模板id 用于分页
                            .replace("TEMPLATE_LABEL_","TEMPLATE_LABEL_"+webpageTemplateTemp.getId())//TEMPLATE_LABEL_ 模板标签id
                    );

                    //模板数据填充
                    root.put("TEMPLATE_TITLE"+webpageTemplateTemp.getId(), webpageTemplateTemp.getTemplateTitle());
                    root.put("TEMPLATE_INFO"+webpageTemplateTemp.getId(), webpageTemplateTemp.getInfo());

                    WebsiteImages websiteImages=new WebsiteImages();
                    websiteImages.setWebpageTemplateId(webpageTemplateTemp.getId());
                    websiteImages.setQueryOrder("queryAsc");
                    List<WebsiteImages> websiteImagesList=websiteImagesService.queryImageList(websiteImages);
                    root.put("WEBSITE_IMAGES_LIST"+webpageTemplateTemp.getId(), websiteImagesList);
                }
                FileUtils.writeFile(ftlUrl+"/"+ftlName+".ftl",bodyHtml.toString());
            }

            FileUtils.createPath(publishUrl.substring(0,publishUrl.lastIndexOf("/")));
            FileUtils.createFile(publishUrl);
            //根据生成的模板 发布页面
            FreeMarkerUtil.analysisTemplate(ftlUrl,ftlName+".ftl",publishUrl,root);

            json = this.setJson(true,returnpreviewUrl,webpage);
        } catch (Exception e) {
            logger.error("AdminWebpageController.ajaxWebpagePreview()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }

    
    /**
     * 刪除页面
     */
    @RequestMapping("/webpage/delete/{id}")
    public String deleteWebpage(HttpServletRequest request, @PathVariable("id") Long id) {
    	try {
    		// 刪除页面
            webpageService.delWebpageById(id);
        } catch (Exception e) {
            logger.error("AdminWebpageController.deleteWebpage()---error", e);
            return setExceptionRequest(request, e);
        }
        return "redirect:/admin/webpage/list";
    }
    
    /**
     * ajax刪除页面
     */
    @RequestMapping("/ajax/webpageDel/{id}")
    @ResponseBody
    public Map<String,Object> ajaxDelWebpage(HttpServletRequest request, @PathVariable("id") Long id) {
    	Map<String, Object> json = new HashMap<String, Object>(4);
    	try {
    		// 刪除页面
            webpageService.delWebpageById(id);

            //根据页面id 删除页面和模板中间表 的记录
            webpageTemplateService.delWebpageTemplateByWebpageId(id);
            Webpage webpage = webpageService.getWebpageById(id);
           /* File file = new File(request.getSession().getServletContext().getRealPath("/")+webpage.getPublishUrl());
            file.delete();*/
            json = setJson(true, null, null);
        } catch (Exception e) {
            logger.error("AdminWebpageController.ajaxDelWebpage()---error", e);
            json=this.setAjaxException(json);
        }
    	return json;
    }

    
    
    /**
     * 根据id修改
     */
    @RequestMapping("/webpage/toUpdate/{id}")
    public ModelAndView toUpdateWebpage(HttpServletRequest request,ModelAndView model, @PathVariable("id") Long id) {
    	model.setViewName(getViewPath("/admin/webpage/webpage_update"));
    	try {
            // 查詢页面
            Webpage webpage = webpageService.getWebpageById(id);
            // 把返回的数据放到model中
            model.addObject("webpage", webpage);

            //页面管理的模板
            WebpageTemplate webpageTemplate=new WebpageTemplate();
            webpageTemplate.setPageId(webpage.getId());
            webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
            List<WebpageTemplate> webpageTemplateList=webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
            model.addObject("webpageTemplateList", webpageTemplateList);
        } catch (Exception e) {
        	model.setViewName(setExceptionRequest(request, e));
            logger.error("AdminWebpageController.toUpdateWebpage()--error", e);
        }
        return model;
    }
    /**
     * 更新页面
     */
    @RequestMapping("/webpage/update")
    public ModelAndView updateWebpage(HttpServletRequest request,ModelAndView model, @ModelAttribute("webpage") Webpage webpage) {
    	model.setViewName("redirect:/admin/webpage/list");
    	try {
            webpageService.updateWebpage(webpage);

            //根据页面id 删除页面和模板中间表 的记录
            webpageTemplateService.delWebpageTemplateByWebpageId(webpage.getId());

            String templateUrlArr[]=request.getParameterValues("templateUrl");
            String templateNameArr[]=request.getParameterValues("templateName");
            String templateSortArr[]=request.getParameterValues("templateSort");

            WebpageTemplate webpageTemplate=new WebpageTemplate();
            webpageTemplate.setPageId(webpage.getId());
            webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
            if(ObjectUtils.isNotNull(templateNameArr)){
                for(int i=0;i<templateUrlArr.length;i++){
                        if(StringUtils.isNotEmpty(templateUrlArr[i])){
                            if (StringUtils.isNotEmpty(templateSortArr[i])){
                            webpageTemplate.setSort(Integer.parseInt(templateSortArr[i]));
                            webpageTemplate.setId(null);
                            webpageTemplate.setTemplateName(templateNameArr[i]);
                            webpageTemplate.setTemplateUrl(templateUrlArr[i].replace(request.getSession().getServletContext().getRealPath("/").replace("\\","/"),"/"));
                            webpageTemplateService.addWebpageTemplate(webpageTemplate);
                        }
                    }
                }
            }
            if(request.getParameter("isPublish").equals("true")){
                //是否发布页面
                webpageService.updWebpagePublish(webpage.getId(),request.getSession().getServletContext().getRealPath("/"));
            }
        } catch (Exception e) {
            logger.error("AdminWebpageController.updateWebpage()--error", e);
            model.setViewName(setExceptionRequest(request, e));
        }
        return model;
    }
	
    /**
     * 查询页面分页列表
     */
    @RequestMapping("/webpage/list")
    public ModelAndView webpageListPage(HttpServletRequest request,ModelAndView model,@ModelAttribute("webpage") Webpage webpage, @ModelAttribute("page") PageEntity page) {
    	model.setViewName(getViewPath("/admin/webpage/webpage_list"));
    	try {
            //按条件查询页面分页
            List<Webpage> webpageList =  webpageService.queryWebpageListPage(webpage, page);
            for (Webpage webpage1 : webpageList){

            }
            model.addObject("rootPath",request.getSession().getServletContext().getRealPath("/"));
            //页面数据
            model.addObject("webpageList",webpageList);
            //分数数据
            model.addObject("page",page);
            //页面查询条件
            model.addObject("webpage",webpage);
        } catch (Exception e) {
        	model.setViewName(setExceptionRequest(request, e));
            logger.error("AdminWebpageController.webpageListPage()--error", e);
        }
        return model;
    }


    /**
     * ajax发布页面
     */
    @RequestMapping("/ajax/webpagePublish/{id}")
    @ResponseBody
    public Map<String,Object> webpagePublish(HttpServletRequest request, @PathVariable("id") Long id) {
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            // 发布页面
            Map<String, String> isSuccess=webpageService.updWebpagePublish(id,request.getSession().getServletContext().getRealPath("/"));
            if (isSuccess.get("success").equals("false")){
                json = setJson(false, isSuccess.get("message"), null);
                return json;
            }
            if (!isSuccess.get("success").equals("true")){
                json = setJson(false,"发布失败",null);
                return json;
            }
            json = setJson(true,null,null);
        } catch (Exception e) {
            logger.error("AdminWebpageController.webpagePublish()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }

    /**
     * 更新webpageTemplate 排序值
     */
    @RequestMapping("/webpageTemplate/updateSort")
    @ResponseBody
    public Map<String,Object> updateSort(HttpServletRequest request){
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            Long current_id = Long.parseLong(request.getParameter("current_id"));
            int current_sort = Integer.parseInt(request.getParameter("current_sort"));
            Long other_id = Long.parseLong(request.getParameter("other_id"));
            int other_sort = Integer.parseInt(request.getParameter("other_sort"));
            webpageTemplateService.updWebpageTemplatesSort(current_sort,current_id,other_sort,other_id);
            json = this.setJson(true,"",null);
        }catch (Exception e){
            logger.error("AdminWebpageController.updateSort()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }
    /*更新webpageTemplate*/
    @RequestMapping("/ajax/fileDel/{id}")
    @ResponseBody
    public Map<String,Object> fileDel(HttpServletRequest request,@PathVariable("id") Long id){
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            Webpage webpage = new Webpage();
            webpage = webpageService.getWebpageById(id);
            String dpath = request.getSession().getServletContext().getRealPath("/");
            String publishUrl = webpage.getPublishUrl();
            String pubUrl = publishUrl.replace("/","/");
            File file = new File(dpath+pubUrl);
            file.delete();
            json = this.setJson(true,"",null);
        }catch (Exception e){
            logger.error("AdminWebpageController.setSort()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }
    /**
     * ajax设为首页
     */
    @RequestMapping("/ajax/setHelloPage/{id}")
    @ResponseBody
    public Map<String,Object> setHelloPage(HttpServletRequest request, @PathVariable("id") Long id) {
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            Webpage webpage = new Webpage();
            Webpage oldHelloPage = new Webpage();
            webpage.setPublishUrl("/index.html");
            Webpage helloPage = webpageService.getWebpageById(id);
            List<Webpage> webpageList = webpageService.queryWebpageList(webpage);
            for (Webpage w : webpageList){
                if (w.getPublishUrl().equals("/index.html")){
                    oldHelloPage = w;
                    String url = oldHelloPage.getPublishUrl();
                    oldHelloPage.setPublishUrl(url.substring(0,url.lastIndexOf("."))+oldHelloPage.getId()+".html");
                    helloPage.setPublishUrl("/index.html");
                }else {
                    helloPage.setPublishUrl("/index.html");
                }
            }
            webpageService.updateWebpage(oldHelloPage);
            webpageService.updateWebpage(helloPage);
            if (!webpageService.updWebpagePublish(oldHelloPage.getId(),request.getSession().getServletContext().getRealPath("/")).get("success").equals("true")||!webpageService.updWebpagePublish(helloPage.getId(),request.getSession().getServletContext().getRealPath("/")).get("success").equals("true")){
                json = this.setJson(false,"设置首页失败",null);
                return json;
            }
            /*数据库保存首页头尾、生成资讯详情页面*/
            this.saveHederFooter(helloPage,request);

            //先发布首页
            webpageService.updWebpagePublish(helloPage.getId(),request.getSession().getServletContext().getRealPath("/"));
            webpageService.publishAll(false,request);
            json = setJson(true, "正在更换页面请稍等！", webpage);

            /*Webpage webpage = webpageService.getWebpageById(id);
            //先发布页面
            webpageService.updWebpagePublish(id);
            //根据页面的发布路径 读取文件内容到index.html
            FileUtils.writeFile(request.getSession().getServletContext().getRealPath("/").replace("\\","/")+"index.html",FileUtils.readLineFile(request.getSession().getServletContext().getRealPath("/").replace("\\","/")+webpage.getPublishUrl()));*/
        } catch (Exception e) {
            logger.error("AdminWebpageController.webpagePublish()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }
    /*
    * 根据首页保存首页头尾、生成资讯详情页面
    * helloPage为首页
    */
    public void saveHederFooter(Webpage helloPage,HttpServletRequest request){
        try {

         /*保存首页模板的头和尾*/
        WebpageTemplate webpageTemplate = new WebpageTemplate();
        webpageTemplate.setPageId(helloPage.getId());
        List<WebpageTemplate> templates = webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
					/*创建头部和尾部的ftl文件*/
        StringBuffer header=new StringBuffer();
        header.append(FileUtils.readLineFile(request.getSession().getServletContext().getRealPath("/")+templates.get(0).getTemplateUrl()));
        FileUtils.writeFile(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/ftl/"+"header.ftl",header.toString());
        StringBuffer footer=new StringBuffer();
        footer.append(FileUtils.readLineFile(request.getSession().getServletContext().getRealPath("/")+templates.get(templates.size()-1).getTemplateUrl()));
        FileUtils.writeFile(request.getSession().getServletContext().getRealPath("/")+"footer.ftl",footer.toString());
					/*获取头部和尾部的动态数据*/
        Map<String, Object> root = new HashMap<>();
        Map<String,Object> webmap=(Map<String,Object>)websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.web.toString()).get(WebSiteProfileType.web.toString());
					/*ctx*/
        root.put("ctx",CommonConstants.contextPath);
					/*首页导航*/
        Map<String,Object> navigatemap = websiteNavigateService.getWebNavigate();
        root.put("title","${title}");
        root.put("websiteNavigates",navigatemap.get("INDEX"));
					/*网站尾部信息*/
        root.put("webmap", webmap);
					/*生成头部和尾部的html页面*/
        FreeMarkerUtil.analysisTemplate(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/ftl/","header.ftl",request.getSession().getServletContext().getRealPath("/")+"header.html",root);
        FreeMarkerUtil.analysisTemplate(request.getSession().getServletContext().getRealPath("/"),"footer.ftl",request.getSession().getServletContext().getRealPath("/")+"footer.html",root);
        String templateFooter = AdminTemplateFileController.txt2String(new File(request.getSession().getServletContext().getRealPath("/")+"footer.html"));
        String templateHeader = AdminTemplateFileController.txt2String(new File(request.getSession().getServletContext().getRealPath("/")+"header.html"));
        //Map<String,Object> templatemap=(Map<String,Object>)websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.template.toString()).get(WebSiteProfileType.template.toString());


					/*把头部和尾部的文件内容写入数据库*/
        Map map2 = new HashMap();
        map2.put("footer",templateFooter);
        map2.put("header",templateHeader);
        Gson gson2 = new Gson();
        JsonParser jsonParser2 = new JsonParser();
        JsonObject jsonObject = jsonParser2.parse(gson2.toJson(map2)).getAsJsonObject();
        if (ObjectUtils.isNotNull(jsonObject) && StringUtils.isNotEmpty(jsonObject.toString())) {// 如果不为空进行更新
            WebsiteProfile websiteProfile = new WebsiteProfile();// 创建websiteProfile
            websiteProfile.setType("template");
            websiteProfile.setDesciption(jsonObject.toString());
            websiteProfileService.updateWebsiteProfile(websiteProfile);
        }
        //生成资讯详情页面
        Map<String, Object> root2 = new HashMap<>();
        root2.put("header",templateHeader);
        root2.put("footer",templateFooter);
        root2.put("ctx",CommonConstants.contextPath);
        root2.put("article","${article}");
        root2.put("content","${content}");
        FreeMarkerUtil.analysisTemplate(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/ftl","article-info.ftl",request.getSession().getServletContext().getRealPath("/")+"WEB-INF/view/inxedu/admin/webpage/articleInfo.jsp",root2);
        }catch (Exception e){
            logger.error("saveHederFooter", e);
        }

    }
    /**
     * 一键发布页面
     */
    @RequestMapping("/webpage/publishStatus")
    public String publishStatus(HttpServletRequest request) {
        webpageService.publishAll(true,request);
        return getViewPath("/admin/webpage/webpage_publishStatus");// 进度
    }

    /**
     * 查询进度
     */
    @RequestMapping("/webpage/progressbar")
    @ResponseBody
    public Object queryprogressbar(HttpServletRequest request) {
        Map<String, Object> json = null;
        try {
                double sumNum = Double.valueOf(WebPagePublishThread.getListSum());
                double listNum = Double.valueOf(WebPagePublishThread.getListNum());
                Map map = new HashMap();
                map.put("sumNum", sumNum);
                map.put("listNum", listNum);
                json = this.setJson(true, "", map);
        } catch (Exception e) {
            logger.error("queryprogressbar", e);
        }
        return json;
    }

    /**
     * ajax还原页面
     */
    @RequestMapping("/ajax/webpageReturn/{id}")
    @ResponseBody
    public Map<String,Object> webpageReturn(HttpServletRequest request,@PathVariable("id") Long id) {
        Map<String, Object> json = new HashMap<String, Object>(4);
        try {
            Webpage webpage = webpageService.getWebpageById(id);
            WebpageTemplate webpageTemplate=new WebpageTemplate();
            webpageTemplate.setPageId(id);
            List<WebpageTemplate> webpageTemplateList=webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
            for(WebpageTemplate webpageTemplateTemp:webpageTemplateList){
                //页面模板 下 模板数据 所有记录表
                websiteImagesService.delImagesByTemplateId(webpageTemplateTemp.getId());
            }


            //先删除当前页面 关联的 模板记录表
            webpageTemplateService.delWebpageTemplateByWebpageId(id);

            String TEMPLATE_NAMEArr[]=new String[]{};
            String TEMPLATE_TITLE[]=new String[]{};
            String TEMPLATE_URL[]=new String[]{};
            String INFO[]=new String[]{};

            //重新添加模板记录   //页面 判断先写死
            if(webpage.getId()==7){//首页模板一
                TEMPLATE_NAMEArr =  new String[]{"公共头部","首页_banner","首页_关于我们","首页_师资力量","首页_新闻资讯","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","首页_banner","关于我们","师资力量","新闻资讯","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/首页_banner.html","/template/templet1/首页_关于我们.html","/template/templet1/首页_师资力量.html","/template/templet1/首页_新闻资讯.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","","ABOUT US/我们怀揣梦想，愿与大家携手，“以开源节流”为宗旨，服务与更多的中小型教育机构和个人，力争借助高速增长的国内互联网在线教育，开拓出领先的在线教育方式，为国内在线教育转型升级创新的过程出自己一份应有的贡献，推动国内在线教育的向上发展。"
                        ,"TEACHERS STRENGTH","NEWS INFORMATION",""};
            }
            else if(webpage.getId()==47){//首页模板二
                TEMPLATE_NAMEArr =  new String[]{"公共头部","首页_banner模板2","首页_考试系统模板2","首页_在线学习模板2","首页_师资力量模板2","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","首页_banner模板2","考试系统","在线学习","师资力量","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/首页_banner模板2.html","/template/templet1/首页_考试系统模板2.html","/template/templet1/首页_在线学习模板2.html","/template/templet1/首页_师资力量模板2.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","","EXAMINATION SYSTEM","ONLINE LEARNING","TEACHER TEAM",""};
            }
            else if(webpage.getId()==48){//首页模板三
                TEMPLATE_NAMEArr =  new String[]{"公共头部","首页_banner模板3","首页_课程介绍模板3","首页_师资团队模板3","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","首页_banner模板3","课程介绍","师资团队","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/首页_banner模板3.html","/template/templet1/首页_课程介绍模板3.html","/template/templet1/首页_师资团队模板3.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","","COURSE INTRODUCTION","TEACHER TEAM",""};
            }
            else if(webpage.getId()==49){//首页模板四
                TEMPLATE_NAMEArr =  new String[]{"公共头部模板2","首页_banner模板4","首页_课程介绍模板4","首页_师资团队模板4","首页_新闻资讯模板4","公共尾部模板2"};
                TEMPLATE_TITLE = new String[]{"公共头部模板2","首页_banner模板4","课程介绍","师资团队","新闻资讯/热门话题","公共尾部模板2"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部模板2.html","/template/templet1/首页_banner模板4.html","/template/templet1/首页_课程介绍模板4.html","/template/templet1/首页_师资团队模板4.html","/template/templet1/首页_新闻资讯模板4.html","/template/templet1/公共尾部模板2.html"};
                INFO = new String[]{"","","COURSE INTRODUCTION","TEACHER TEAM","NEW INFORMATION/HOT TOPIC",""};
            }

            if(webpage.getId()==1){//首页模板五
                TEMPLATE_NAMEArr =  new String[]{"公共头部模板5","首页_banner模板5","课程分类模板5","关于我们模板5","留学资讯模板5","优秀学员模板5","公共尾部模板5"};
                TEMPLATE_TITLE = new String[]{"公共尾部模板5","首页_banner模板5","课程分类","关于我们","留学资讯","优秀学员","公共尾部模板5"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部模板5.html","/template/templet1/首页_banner模板5.html","/template/templet1/首页_课程分类模板5.html"
                        ,"/template/templet1/首页_关于我们模板5.html","/template/templet1/首页_留学资讯模板5.html","/template/templet1/首页_优秀学员模板5.html","/template/templet1/公共尾部模板5.html"};
                INFO = new String[]{"","","针对性提高，个性化教学,一起快乐学习","业精于勤，我们赢得了超过200多家大型公司、集团的认可，越来越多的同学选择加入我们的团队，成就更加美好的未来。"
                        ,"加入瑞思语言培训，收货一个成功的未来，圆你一个出国的梦想，携手并进，共赴明天。","加入瑞思语言培训，收货一个成功的未来，圆你一个出国的梦想，携手并进，共赴明天。",""};
            }
            if(webpage.getId()==2){//首页模板六
                TEMPLATE_NAMEArr =  new String[]{"公共头部模板6","首页_banner模板6","首页_迎战未来的4大因素6","首页_服务需求模板6","首页_职业资讯模板6","首页_生活环境模板6","公共头部模板6"};
                TEMPLATE_TITLE = new String[]{"公共头部模板6","","迎战未来的4大因素","为你提供全方位、更全面的选择需求","职业教育：世界因我而美好","为您提供良好的学习环境及生活环境","公共头部模板6"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部模板6.html","/template/templet1/首页_banner模板6.html","/template/templet1/首页_迎战未来的4大因素6.html"
                        ,"/template/templet1/首页_服务需求模板6.html","/template/templet1/首页_职业资讯模板6.html","/template/templet1/首页_生活环境模板6.html","/template/templet1/公共尾部模板6.html"};
                INFO = new String[]{"","","","","","为您提供良好的学习环境及生活环境/行业唯一自建专属基地/专供学员学习使用/星级标准安全保障/专聘外交独家指导/一对一针对性服务指导",""};
            }
            if(webpage.getId()==3){//首页模板七
                TEMPLATE_NAMEArr =  new String[]{"公共头部模板7","首页_banner模板7","首页_特色班级模板7","首页_优秀学员模板7","首页_师资团队模板7","首页_新闻资讯模板7","公共尾部模板6"};
                TEMPLATE_TITLE = new String[]{"公共头部模板7","首页_banner模板7","特色班级","部分高分学员成绩及入取院校","我们的团队","学习信息免费推送，你的竞争软实力","公共尾部模板6"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部模板7.html","/template/templet1/首页_banner模板7.html","/template/templet1/首页_特色班级模板7.html"
                        ,"/template/templet1/首页_优秀学员模板7.html","/template/templet1/首页_师资团队模板7.html","/template/templet1/首页_新闻资讯模板7.html","/template/templet1/公共尾部模板6.html"};
                INFO = new String[]{"","","Features Class","选择我们，选择成功","Our team","选择我们，选择成功",""};
            }

            else if(webpage.getId()==8){//课程
                TEMPLATE_NAMEArr =  new String[]{"公共头部","课程_广告图","课程_优势介绍","课程_精品课程","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","课程_广告图","课程优势","精品课程","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/课程_广告图.html","/template/templet1/课程_优势介绍.html","/template/templet1/课程_精品课程.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","","","EXCELLENT CJRRICULUM",""};
            }
            else if(webpage.getId()==11){//资讯列表
                TEMPLATE_NAMEArr =  new String[]{"公共头部","资讯_资讯列表","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","资讯列表/资讯排行","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/资讯_资讯列表.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","INFORMATION LIST/INFORMATION LIST",""};
            }
            else if(webpage.getId()==41){//关于我们
                TEMPLATE_NAMEArr =  new String[]{"公共头部","关于我们_广告图一","关于我们_我们是谁","关于我们_我们的优势","关于我们_我们的服务","关于我们_找到我们","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","关于我们_广告图一","我们是谁","我们的优势","我们的服务","找到我们","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/关于我们_广告图一.html","/template/templet1/关于我们_我们是谁.html","/template/templet1/关于我们_我们的优势.html","/template/templet1/关于我们_我们的服务.html","/template/templet1/关于我们_找到我们.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","","WHO ARE WE",
                        "OUR GOAL","OUR SERVICE","FIND US",""};
            }
            else if(webpage.getId()==46){//名师
                TEMPLATE_NAMEArr =  new String[]{"公共头部","师资_广告","师资_优势介绍","师资_讲师团队","师资_学员心声","公共尾部"};
                TEMPLATE_TITLE = new String[]{"公共头部","师资_广告","优势介绍","讲师团队","学员心声","公共尾部"};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部.html","/template/templet1/师资_广告.html","/template/templet1/师资_优势介绍.html","/template/templet1/师资_讲师团队.html","/template/templet1/师资_学员心声.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","","","TEACHER TEAM","STUDENTS VOICE",""};
            }
            else if(webpage.getId()==60){//测试页面
                TEMPLATE_NAMEArr =  new String[]{"公共头部模板1","首页_关于我们","公共尾部"};
                TEMPLATE_TITLE = new String[]{"","关于我们",""};
                TEMPLATE_URL = new String[]{"/template/templet1/公共头部模板1.html","/template/templet1/首页_关于我们.html","/template/templet1/公共尾部.html"};
                INFO = new String[]{"","关于我们介绍",""};
            }
            addWebpageTemplate(TEMPLATE_NAMEArr,TEMPLATE_TITLE,TEMPLATE_URL,INFO,webpage.getId());

            // 发布页面
            webpageService.updWebpagePublish(id,request.getSession().getServletContext().getRealPath("/"));
            json = setJson(true,null,webpage);
        } catch (Exception e) {
            logger.error("AdminWebpageController.webpagePublish()---error", e);
            json=this.setAjaxException(json);
        }
        return json;
    }

    /**
     * 添加模板数据
     * @param TEMPLATE_NAMEArr 模板名称
     * @param TEMPLATE_TITLE 模板标题
     * @param TEMPLATE_URL 模板地址
     * @param INFO 模板描述
     * @param webpageId 页面id
     */
    public void addWebpageTemplate(String TEMPLATE_NAMEArr[],String TEMPLATE_TITLE[],String TEMPLATE_URL[],String INFO[],Long webpageId){
        Long returnwebpageTemplateId=0L;
        WebpageTemplate webpageTemplate=null;
        for (int i=0;i<TEMPLATE_NAMEArr.length;i++){
            webpageTemplate=new WebpageTemplate();
            webpageTemplate.setPageId(webpageId);
            webpageTemplate.setTemplateName(TEMPLATE_NAMEArr[i]);
            webpageTemplate.setTemplateTitle(TEMPLATE_TITLE[i]);
            webpageTemplate.setTemplateUrl(TEMPLATE_URL[i]);
            webpageTemplate.setInfo(INFO[i]);
            webpageTemplate.setSort(i);
            webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
            returnwebpageTemplateId=webpageTemplateService.addWebpageTemplate(webpageTemplate);

            //添加模板数据
            websiteImagesService.addTemplateData(webpageTemplate.getTemplateUrl(),returnwebpageTemplateId);
        }
    }

}



